<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\model\AccountModel;
use think\facade\Db;

class Login extends  BaseController
{
    /**
     * @var  AccountModel
     */
    private $model;

    public function initialize()
    {
        $this->model = new AccountModel();
    }

    public function index()
    {
        $result   = [
            "status" => "no",
            "data"   => [],
            "msg"    => "查找失败"
        ];
        $userName = $this->request->param("name", "");
        $password = $this->request->param("password", "");

        if (empty($userName)) {
            $result["msg"] = "请输入登录账号";
            return json($result);
        }

        if (empty($password)) {
            $result["msg"] = "请输入登录密码";
            return json($result);
        }

        //查找account
        $account = Db::table("gy_account")
            ->where('type',3)
            ->where('account_name', $userName)->find();
        if (empty($account)) {
            $result["msg"] = "登录账号不存在";
            return json($result);
        }

        $loginPwd = $this->model->password($password);
        if ($loginPwd != $account['account_pwd']) {
            $result["msg"] = "登录密码错误";
            return json($result);
        }

        $token = $this->model->getToken($account['account_name'], $account['account_pwd']);
        $time  = date('Y-m-d H:i:s');
        $ip    = $this->request->ip();

        $loginData = [
            'token'      => $token,
            "last_login" => $time,
            "last_ip"    => $ip
        ];

        $loginResult = Db::table("gy_account")
            ->where('account_id', $account['account_id'])
            ->update($loginData);

        if ($loginResult) {
            $result['status'] = 'ok';
            $result['msg']    = '登录成功';
            $result['data']   = [
                'uid'      => $account['account_id'],
                'user'     => $account['account_name'],
                'limits'   => $account['limits'],
                'token'    => $token,
                'expire'   => strtotime($time) + 60 * 60 * 24 * 7
            ];

        }
        return json($result);
    }
}